<template>
  <div>
    <el-card>
      <div class="header">
        <h2 class="title" style="font-size: 18px">系统功能开关<span
            style="color:#d2d7e3;font-size:20px;margin-top:10px;padding-left:10px;padding-bottom:5px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 420px;" slot="content">系统功能项目关闭后，策略将不再生效，表示不启用该功能项目。状态字段有*表示修改该配置后需要重启终端资产电脑才能生效</div>
            </el-tooltip>
          </span></h2>
        <el-button type="primary" @click="saveConfig">保存配置</el-button>
      </div>
      <el-table :data="features" border style="width: 100%" row-key="name"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="功能配置" width="300">
          <template slot-scope="scope">
            <span>{{ scope.row.displayName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="依赖关系" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.dependentOn">{{ descriptions[scope.row.dependentOn] || scope.row.dependentOn }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <el-switch v-if="scope.row.status !== undefined" v-model="scope.row.status"
              :disabled="featureDisabled[scope.row.name]"></el-switch>
            <span v-if="scope.row.description && scope.row.description.includes('需重启PC')"
              style="color: red; margin-left: 5px;">*</span>
          </template>
        </el-table-column>
        <!-- 新增描述列 -->
        <el-table-column label="描述">
          <template slot-scope="scope">
            <span>{{ scope.row.detailDescription || '无' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'

export default {
  data() {
    // 从提供的 JSON 创建描述映射
    const detailDescriptions = {
      TechImpl: {
        UseDriver: '通过内核级驱动实现深度监控，确保进程审计和USB审计无死角',
      },
      SecAudit: {
        ProcessAudit: '实时监控所有进程活动，守护系统安全',
        SetupCtrl: '智能拦截未经授权的软件安装行为',
        USBStorageAudit: '全面管控U盘等移动存储设备的使用',
        NetAudit: '智能过滤危险网络连接，筑起安全防火墙',
        NetcardCtrl: '灵活管理网卡启用状态，切断非法外联',
      },
      RealMon: {
        RealtimeScreen: '如同亲临现场般实时查看终端屏幕',
        RemoteCtrl: '远程指挥终端执行关键操作，运筹帷幄',
      },
      LogAnalysis: {
        ScreenRecord: '自动留存屏幕快照，打造可视化工作档案',
        IMChat: '完整记录即时通讯内容，沟通有迹可循',
        WorkFlow: '智能追踪工作流水，还原操作轨迹',
        WindowProc: '精准统计工作绩效，量化产出成果',
        OSLog: '全面采集系统日志，构建安全证据链',
        InstalledHardware: '自动盘点硬件资产，设备信息一目了然',
        HardwareChange: '实时感知硬件异动，防盗防拆解',
        InstalledSoftware: '自动清点软件资产，杜绝盗版风险',
        SoftwareChange: '敏锐捕捉软件变更，防范恶意植入',
      },
      SecAwer: {
        BaselineCheck: '自动化安全体检，快速发现合规缺口',
        NetService: '网络业务健康监测',
        ProcAccessNet: '全量记录进程网络行为，揪出可疑连接',
        ProcRun: '完整追踪进程生命周期，让恶意程序无所遁形',
        AutoRun: '全面掌握自启动项，斩断病毒温床',
        ShareDir: '智能发现共享目录，堵住数据泄露漏洞',
        IllegalPort: '精准识别高危端口，及时消除隐患',
        OpenPorts: '全景扫描开放端口，把好网络安全门',
        DNSAccess: '深度分析DNS请求，阻断恶意域名解析',
        PeripheralCtrl: '精细管控外设使用，杜绝数据走私',
        ServiceInfos: '全面掌握服务状态，守护系统核心',
        URLMonitor: '记录用户的URL访问'
      },
      RunAssist: {
        RemoteDesk: '安全稳定的远程协助，随时随地排忧解难',
        FileShareSevice: '快速搭建安全文件共享，团队协作更高效',
        SoftwareManager: '一站式软件管理平台，可信软件安装尽在掌握',
        SoftwareDispatch: '批量静默部署软件，省时省力更省心',
        EnergySave: '智能调节能耗设置，践行绿色办公',
        CorpIdentity: '统一终端视觉形象，彰显企业品牌魅力',
      },
    };

    return {
      features: [], // 当前的功能数据
      initialFeatures: [], // 保存初始状态
      // 模块中文名称映射
      moduleNames: {
        TechImpl: '启用驱动',
        SecAudit: '安全规则',
        RealMon: '实时监测',
        LogAnalysis: '日志分析',
        SecAwer: '安全感知',
        RunAssist: '业务配置',
      },
      // 功能描述映射表（用于状态列的描述）
      descriptions: {
        UseDriver: '使用驱动版本/应用层版本 需重启PC',
        USBStorageAudit: '移动存储审计 需重启PC',
        SoftwareDispatch: '软件分发 需重启PC',
        ProcessAudit: '进程审计 需重启PC',
        SetupCtrl: '安装软件控制',
        NetAudit: '网络审计',
        RealtimeScreen: '实时屏幕',
        RemoteCtrl: '远程控制',
        ScreenRecord: '屏幕录像',
        IMChat: '沟通回溯',
        WorkFlow: '工作流水',
        WindowProc: '工作绩效',
        OSLog: '操作系统',
        HardwareChange: '硬件变更检测',
        InstalledHardware: '硬件信息',
        SoftwareChange: '软件变更检测',
        InstalledSoftware: '安装软件',
        BaselineCheck: '基线核查',
        NetService: '网络业务',
        ProcAccessNet: '软件外联',
        ProcRun: '进程加载',
        AutoRun: '开机自启',
        ShareDir: '共享目录',
        IllegalPort: '高危端口',
        OpenPorts: '开放端口',
        DNSAccess: '域名解析',
        PeripheralCtrl: '外设审计',
        ServiceInfos: '系统服务',
        RemoteDesk: '远程桌面',
        FileShareSevice: '文件共享',
        EnergySave: '节能规则',
        CorpIdentity: '企业形象',
        SoftwareManager: '软件管家',
        NetcardCtrl: '网卡控制',
        URLMonitor: 'URL访问记录'
      },
      // 依赖关系映射表
      dependencies: {
        HardwareChange: 'InstalledHardware',
        SoftwareChange: 'InstalledSoftware',
        SetupCtrl: 'ProcessAudit',
      },
      // 详细描述映射表
      detailDescriptions,
    };
  },
  computed: {
    // 计算每个功能的禁用状态
    featureDisabled() {
      const disabled = {};
      this.features.forEach(module => {
        if (module.children) {
          module.children.forEach(feature => {
            if (feature.dependentOn) {
              const depFeature = this.findFeatureByName(feature.dependentOn);
              disabled[feature.name] = depFeature ? !depFeature.status : false;
            } else {
              disabled[feature.name] = false;
            }
          });
        }
      });
      return disabled;
    },
  },
  created() {
    this.getData();
  },
  methods: {
    async getData() {
      const data = {
        Filter: {
          FileName: 'sys_func_cfg.json',
        },
      };
      const res = await connrequest('GetUICommonParam', data);
      if (!res) {
        this.features = [];
        return;
      }
      res.Data = res.Data || [];
      // 将嵌套 JSON 转换为树形表格所需的数据结构
      this.features = Object.entries(res.Data).map(([moduleName, functionalities]) => ({
        name: moduleName,
        displayName: this.moduleNames[moduleName] || moduleName, // 显示模块的中文名称
        children: Object.entries(functionalities).map(([funcName, status]) => ({
          name: funcName,
          status: status === 1, // 转换为布尔值
          description: this.descriptions[funcName] || '',
          displayName: this.descriptions[funcName] || funcName, // 显示功能的中文描述
          dependentOn: this.dependencies[funcName] || null,
          detailDescription: this.detailDescriptions[moduleName]?.[funcName] || '', // 添加详细描述
        })),
      }));
      // 在加载数据后，深拷贝初始状态
      this.initialFeatures = JSON.parse(JSON.stringify(this.features));
    },
    // 辅助方法：根据名称查找功能项
    findFeatureByName(name) {
      for (const module of this.features) {
        if (module.children) {
          const feature = module.children.find(f => f.name === name);
          if (feature) return feature;
        }
      }
      return null;
    },
    // 保存配置
    async saveConfig() {
      const json = {};
      this.features.forEach(module => {
        if (module.children) {
          json[module.name] = {};
          module.children.forEach(feature => {
            json[module.name][feature.name] = feature.status ? 1 : 0;
          });
        }
      });

      // 检查是否有需要重启的功能项状态发生了变化
      let needRestartChanged = false;
      this.features.forEach((module, moduleIndex) => {
        if (module.children) {
          module.children.forEach((feature, featureIndex) => {
            const initialFeature = this.initialFeatures[moduleIndex]?.children[featureIndex];
            if (
              initialFeature &&
              feature.description.includes('需重启PC') &&
              feature.status !== initialFeature.status
            ) {
              needRestartChanged = true;
            }
          });
        }
      });

      // 如果需要重启的功能项有变化，弹出确认框
      if (needRestartChanged) {
        let confirmed = false;
        try {
          await this.$confirm(
            '本次保存包含需要重启的功能项的变化，保存后需重启终端资产电脑才能生效。是否继续？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          );
          confirmed = true;
        } catch (e) {
          confirmed = false;
        }

        if (!confirmed) {
          // 用户取消时，恢复到初始状态
          this.features = JSON.parse(JSON.stringify(this.initialFeatures));
          return; // 中止保存
        }
      }

      // 执行保存操作
      const data = {
        Filter: {
          FileName: 'sys_func_cfg.json',
        },
        Data: {
          ...json,
        },
      };
      const res = await connrequest('SetUICommonParam', data);
      if (res.Status.StatusCode === 0) {
        this.$message.success('保存成功');
        this.getData(); // 刷新数据
        this.initialFeatures = JSON.parse(JSON.stringify(this.features)); // 更新初始状态
      }
    },
  },
};
</script>

<style scoped>
.el-card {
  margin: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
}
</style>